class Api::V1::SkusController < Api::V1::BaseController
  skip_before_action :authenticate_request!
  before_action :authenticate_request

  def index
    @skus = Sku.joins(:spu).where(:spus => {state: :onsale, published: true})
    if params[:search_key].presence
      @skus = @skus.where("spus.name LIKE ?", "%#{params[:search_key]}%")
    end
    if params[:shop_category_id].presence
      @skus = @skus.where(:spus => {shop_category_id: params[:shop_category_id]})
    end
    if params[:brand_id].presence
      @skus = @skus.where(:spus => {brand_id: params[:brand_id]})
    end
    if params[:sales_price].presence
      @skus = @skus.order("min(skus.sale_price) #{params[:sales_price]}")
    elsif params[:sales_volumn].presence
      @skus = @skus.order("spus.sales_volume DESC")
    elsif params[:newest].presence
      @skus = @skus.order("created_at DESC")
    end
    if params[:handpick].presence
      @skus = @skus.where(:spus => {handpick: ActiveModel::Type::Boolean.new.cast(params[:handpick])})
    end
    if params[:promotion].presence
      @skus = @skus.where(:spus => {promotion: ActiveModel::Type::Boolean.new.cast(params[:promotion])})
    end
    if @current_area.presence
      @skus = spus_where_area(@skus, @current_area.id)
    end
    @skus = @skus.page(params[:page]).per(params[:per])
  end
end
